using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Buffers;
using Newtonsoft.Json;
using System.Threading;
using Project.Commom.Model;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Collections.Generic;
using Project.SemanticKernelService;
using Project.SemanticKernelService.Model;

namespace Project.WebSocketService
{
    /// <summary>
    /// Socket服务
    /// </summary>
    public class SocketService : ISocketService
    {
        private readonly IChatService _chatService;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="chatService"></param>
        public SocketService(IChatService chatService)
        {
            _chatService = chatService;
        }

        /// <summary>
        /// WebSocket消息回复
        /// </summary>
        /// <param name="webSocket"></param>
        /// <param name="openai"></param>
        /// <returns></returns>
        async Task ISocketService.WebSocketReceive(WebSocket webSocket)
        {
            var buffer = ArrayPool<byte>.Shared.Rent(1024);
            try
            {
                while (webSocket.State == WebSocketState.Open)
                {
                    var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "关闭连接", CancellationToken.None);
                        return;
                    }

                    using (var memoryStream = new MemoryStream())
                    {
                        memoryStream.Write(buffer, 0, result.Count);

                        while (!result.EndOfMessage)
                        {
                            result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                            memoryStream.Write(buffer, 0, result.Count);
                        }

                        var binaryData = memoryStream.ToArray();

                        if (binaryData.Length < 4)
                            throw new InvalidOperationException("接收到的二进制数据不完整");

                        var jsonLength = BitConverter.ToInt32(binaryData, 0);

                        if (BitConverter.IsLittleEndian)
                        {
                            var lengthBytes = binaryData.Take(4).ToArray();
                            Array.Reverse(lengthBytes);
                            jsonLength = BitConverter.ToInt32(lengthBytes, 0);
                        }

                        if (jsonLength <= 0 || jsonLength > int.MaxValue - 4)
                            throw new InvalidOperationException("JSON 长度无效");

                        if (binaryData.Length < 4 + jsonLength)
                            throw new InvalidOperationException("接收到的二进制数据不完整");

                        string json = Encoding.UTF8.GetString(binaryData, 4, jsonLength);

                        MessageQuery messageQuery = JsonConvert.DeserializeObject<MessageQuery>(json);

                        if (!string.IsNullOrEmpty(messageQuery.Content))
                        {
                            MessageRequest dto = new MessageRequest();
                            dto.Reasoning = messageQuery.Reasoning;
                            dto.Content = messageQuery.Content;
                            dto.FilePath = messageQuery.FilePath;
                            dto.MimeType = messageQuery.MimeType;

                            if (!string.IsNullOrEmpty(messageQuery?.FileData))
                            {
                                dto.FileData = Convert.FromBase64String(messageQuery.FileData);
                            }

                            //数据消息结果
                            MessageResult messageResult = new MessageResult();

                            //获取模型响应
                            IAsyncEnumerable<MessageResult> messageResults = _chatService.GetStreamingChatResponseAsync(dto);

                            await foreach (MessageResult response in messageResults)
                            {
                                // 1.更新 messageResult 属性
                                messageResult = response;

                                // 2. 将整个 messageResult 对象序列化为 JSON 字符串
                                string jsonMessage = JsonConvert.SerializeObject(messageResult);

                                // 3. 将 JSON 字符串转换为 UTF-8 字节数组
                                byte[] responseBytes = Encoding.UTF8.GetBytes(jsonMessage);

                                // 4. 通过 WebSocket 发送
                                await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageResult messageResult = new MessageResult();

                // 1.更新 Content 属性
                messageResult.Content = "服务器繁忙，请稍后重试！"; ;

                // 2. 将整个 MessageResult 对象序列化为 JSON 字符串
                string jsonMessage = JsonConvert.SerializeObject(messageResult);

                // 3. 将 JSON 字符串转换为 UTF-8 字节数组
                byte[] responseBytes = Encoding.UTF8.GetBytes(jsonMessage);

                // 4. 通过 WebSocket 发送
                await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }
    }
}
